package udp2;

import java.net.*;

public class MulticastSocketUDP extends Thread {
	MulticastSocket socket=null;
	InetAddress net=null;

	 MulticastSocketUDP() throws Exception {
		 /*
		  * 创建IP地址的封装类,此IP地址不是本机的IP地址,而是D类IP地址
		  *  D类IP地址专门用于多点广播
		  */
		net = InetAddress.getByName("224.0.4.0");//D类IP地址范围是(224.0.0.0~239.225.225.225)
		socket = new MulticastSocket(9999);// 创建多点广播套接字
		socket.setTimeToLive(1);//指定发送的范围是本机网络
		socket.joinGroup(net);//将InetAddress对象加入广播组
	}

	public void run() {
		while (true) {
			byte a[] = "打你一万年".getBytes();
			DatagramPacket packet = new DatagramPacket(a, a.length, net, 8888);//创建数据报包
			System.out.println(new String(a,0,a.length));//打印
			try {
				socket.send(packet);//发送数据报
				sleep(3000);//休眠3秒
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args) throws Exception {
		new MulticastSocketUDP().start();//启动线程
		
	}

}
